package com.evo.chat.web.controller;

import com.evo.chat.common.Result;
import com.evo.chat.common.ResultEnum;
import com.evo.chat.common.base.BaseController;
import com.evo.chat.common.utils.ResultUtil;
import com.evo.chat.web.domain.UserInfo;
import com.evo.chat.web.domain.Words;
import com.evo.chat.web.repository.UserRepository;
import com.evo.chat.web.service.impl.WordsServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Optional;

/**
 * 留言
 * @author luwenzheng
 * date 2020-02-08
 */
@RestController
@RequestMapping("/words")
@CrossOrigin
public class WordsController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    WordsServiceImpl service;

    @Autowired
    UserRepository userRepository;

    @PostMapping(value = "/create")
    public Result createWords(@Valid Words words, BindingResult bindResult) {

        if (bindResult.hasErrors()) {
            return ResultUtil.error(-1, bindResult.getFieldError().getDefaultMessage());
        }

        Integer userId = verifyToken();
        // todo 存在问题，redis查询出来的userinfo 直接使用会报错 需要跟进查询问题
        Optional<UserInfo> byId = userRepository.findById(userId);
        UserInfo userInfo = byId.get();
        if (!userInfo.isAllowWords()) {
            return ResultUtil.error(ResultEnum.USER_NOT_ALLOW_WORDS);
        }
        words.setUser(userInfo);
        return service.createWord(words);
    }

    @PostMapping(value = "/query")
    public Result query() {
        Integer userId = verifyToken();
        return service.queryUserWords(userId);
    }

    @PostMapping(value = "/list")
    public Result queryByUserName(@RequestParam(value = "name") String name) {
        verifyToken();
        return service.queryWordsByName(name);
    }

    @PostMapping(value = "/del")
    public Result delWords(@RequestParam(value = "id", required = false) Integer id) {
        if (StringUtils.isEmpty(id)) {
            return ResultUtil.error(ResultEnum.PARAMETER_VALIDATION_ERROR);
        }
        verifyToken();
        return service.delWords(id);
    }

}
